package service

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/go-xorm/xorm"

	"im/common"
	"im/dao"
	"im/errcode"
	"im/model"
	"im/requests"
	"im/service/orm"
)

type UserService struct {
	db *xorm.Engine
}

func NewUserService() *UserService {
	return &UserService{db: orm.GetDB()}
}

func (s UserService) UpdateById(user model.Users, data requests.UsersPutParams) error {
	err := dao.NewUsersDao().UpdateById(user.Id, data)
	if err != nil {
		return err
	}
	err = NewRongYun().UpdateUser(strconv.FormatInt(user.Id, 10), data)
	return err
}
func (s UserService) geneUserId(account string) string {
	rand.Seed(time.Now().UnixNano())
	return fmt.Sprintf("%s_%d", common.Sha1(account, 10), rand.Int())
}

// 创建一个账号
func (s *UserService) Create(appsId uint, param requests.UsersAccessPost) (token string, err error) {
	var user model.Users
	exist, err := s.db.Where("apps_id=?", appsId).Where("account=?", param.UserId).Get(&user)
	if err != nil {
		err = errcode.NewError(errcode.DaoFailed, err)
		return
	}
	if !exist {
		account := strconv.FormatInt(param.UserId, 10)
		user = model.Users{
			UsersVisually: model.UsersVisually{
				UserModifiable: model.UserModifiable{
					Nickname: param.NickName,
					Avatar:   param.Avatar,
					CoverImage:param.CoverImage,
				},
				Account: account,
			},
			AppsId: appsId,
			Status: 1,
		}
		_, err = s.db.InsertOne(&user)
		if err != nil {
			err = errcode.NewError(errcode.DaoFailed, err)
			return
		}
	}
	if user.Token != "" {
		return user.Token, nil
	}
	token, err = NewRongYun().GetToken(user)
	if err != nil {
		return
	}
	_, err = s.db.Where("id=?", user.Id).Update(model.Users{
		Token: token,
	})
	if err != nil {
		err = errcode.NewError(errcode.DaoFailed, err)
		return
	}
	return
}

func (s *UserService) GetInfoMapByIds(ids ...int64) (map[int64]model.Users, error) {
	return dao.NewUsersDao().GetInfoMapByIds(ids...)
}
func (s *UserService) GetInfoById(id int64) (user model.Users, err error) {
	infos, err := s.GetInfoMapByIds(id)
	if err != nil {
		return
	}
	if _, ok := infos[id]; !ok {
		err = errcode.NewError(errcode.RequestParamInvalid)
		return
	}
	return infos[id], nil
}
